﻿<%@ WebHandler Language="C#" Class="ZSStockReturnApplyBillHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

//Description:退库单处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:longb
//create Date:2023-02-27
public class ZSStockReturnApplyBillHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSMfgOrderIBusiness m_MfgOrderObj = uMESBusinessFactory.instance.GetuLMSMfgOrderObject();
    public void ProcessRequest (HttpContext context) {
       try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetOrderList"://订单查询
                    GetOrderList(context);
                    break;
                case "saveStockReturnBillData"://保存退库申请单信息
                    saveStockReturnBillData(context);
                    break;
                case "getStockReturnApplyData"://查询退库申请单信息
                    getStockReturnApplyData(context);
                    break;
                case "getStockReturnApplyDataByPageSize"://查询退库申请单信息(分页)
                    getStockReturnApplyDataByPageSize(context);
                    break;
                case "updateStockReturnBillData"://更新退库申请单信息
                    updateStockReturnBillData(context);
                    break;    
                case"deleteStockReturnBillData"://删除退库申请单信息
                    deleteStockReturnBillData(context);
                    break;        
            }
        }
       catch (Exception ex)
       {
           var result = new uMESProcessResult();
           result.Result = false;
           result.Message = ex.Message;
           context.Response.ContentType = "text/html";
           context.Response.Write(JsonConvert.SerializeObject(result));
       }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    public void GetOrderList(HttpContext context) 
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();

        var sql = @"SELECT m.MFGORDERID,m.MFGORDERNAME,ot.ordertypename,u.ATTRIBUTEVALUE MachineNO,u1.ATTRIBUTEVALUE mfgYpe 
                ,PB.PRODUCTNAME,P.DESCRIPTION PRODUCTDESCRIPTION,to_char(m.FACTORYSTARDATE,'yyyy-MM-dd')FACTORYSTARDATE ,to_char(m.FACTORYCOMPLETIONDATE,'yyyy-MM-dd') FACTORYCOMPLETIONDATE
                ,pf.productfamilyname
                FROM MFGORDER m 
                LEFT JOIN Ordertype ot on ot.ordertypeid=m.ordertypeid
                LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
                LEFT JOIN USERATTRIBUTE u1 ON u1.PARENTID =m.MFGORDERID AND u1.USERATTRIBUTENAME ='订单类别'
                LEFT JOIN PRODUCT P  ON P.PRODUCTID = GET_SPLIT_MFGORDER_PRODUCTID(m.mfgorderid) 
                LEFT JOIN PRODUCTBASE PB  ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                LEFT JOIN WORKFLOW W  ON W.WORKFLOWID =P.WORKFLOWID 
                LEFT JOIN Workflowproductfamilylist wff ON wff.workflowid=w.workflowid 
                LEFT JOIN productfamily pf ON wff.productfamilylistid=pf.productfamilyid 
                WHERE m.QTY>0 AND m.MFGORDERID IN (select distinct mfgorderid from enginepartplan) ";
        sql += " AND m.FACTORYID='" + m_UserInfo.FactoryID + "'";
        if (!string.IsNullOrWhiteSpace(para["mfgOrderName"]))
        {
            sql += " AND m.MFGORDERNAME LIKE '%" + para["mfgOrderName"] + "%'";
        }
        if(!string.IsNullOrWhiteSpace(para["Machine"])){
            sql += "  And u.attributevalue LIKE '%" + para["Machine"] + "%'";
        }
        var OrderTypeName="PD05,PD06,PD09,PD11,PD12,PD13,PD14";
         if (para["OrderTypeIndex"] =="1") {
             sql += string.Format(" AND ot.OrderTypeName in ('{0}') ", OrderTypeName.Replace(",", "','"));
         }else{
             sql += string.Format("  AND ot.OrderTypeName not in ('{0}') ", OrderTypeName.Replace(",", "','"));   
         }
         var paraPage = new uMESPagingDataDTO();
         paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
         paraPage.PageSize = Convert.ToInt32(pageSize);
         paraPage.strSQL = sql;
         result = DatabaseHelper.RunProcedureForPage(paraPage);
       
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存退库申请单信息
    /// </summary>
    /// <param name="context"></param>
    public void saveStockReturnBillData(HttpContext context) {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var ReturnType = context.Request["ReturnType"].ToString();
        var mfgOrderID = context.Request["mfgOrderID"].ToString();
        var sqlArr = new ArrayList();
        var dtCount = DatabaseHelper.Query_ReturnDatTable("select COUNT(distinct STOCKRETURNAPPLYBILLNO)+1 C From ZSStockReturnApplyBill");
        var strSequence = "000000" + (dtCount.Rows.Count == 0 || dtCount.Rows[0]["C"].ToString()=="0" ? "1" : dtCount.Rows[0]["C"].ToString());
        var BillNo = "TKSQ-" + DateTime.Now.ToString("yyyy") + "-" + m_UserInfo.FactoryCode + "-" + strSequence.Substring(strSequence.Length - 4);
        var insertSQL = @"insert into ZSStockReturnApplyBill(ZSSTOCKRETURNAPPLYBILLID,STOCKRETURNAPPLYBILLNO,STOCKRETURNTYPE,MFGORDERID,PRODUCTID,PRODUCTBATCHNO,STOCKRETURNNUM,STOCKRETURNREASON,CREATEDATE,CREATEEMPLOYEEID,STATUS)
                        VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',sysdate,'{8}','0')";
        foreach(DataRow row in dt.Rows)
        {
            var GID = Guid.NewGuid().ToString();
            sqlArr.Add(string.Format(insertSQL, GID, BillNo, ReturnType, mfgOrderID, row["PRODUCTID"], row["PRODUCTBATCHNO"], row["STOCKRETURNNUM"], row["STOCKRETURNREASON"],m_UserInfo.EmployeeID));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询退库申请单信息
    /// </summary>
    public void getStockReturnApplyDataByPageSize(HttpContext context) 
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var dic = JsonConvert.DeserializeObject<Dictionary<string,string>>(context.Request["data"].ToString());
        var SelSQL = GetStockReturnApplyzSql(context);
        if (!string.IsNullOrWhiteSpace(dic["Machine"].ToString())) 
        {
            SelSQL += " and u.ATTRIBUTEVALUE like '%" + dic["Machine"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["MfgOrdername"].ToString()))
        {
            SelSQL += " and m.MFGORDERNAME like '%" + dic["MfgOrdername"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["billname"].ToString()))
        {
            SelSQL += " and sr.STOCKRETURNAPPLYBILLNO like '%" + dic["billname"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["status"].ToString()))
        {
            SelSQL += " and sr.STATUS= '" + dic["status"].ToString() + "'";
        }

        if (!string.IsNullOrWhiteSpace(dic["startdate"].ToString()))
        {
            SelSQL += " and to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')>= '" + dic["startdate"].ToString() + "'";
        }
        if (!string.IsNullOrWhiteSpace(dic["enddate"].ToString()))
        {
            SelSQL += " and to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')<= '" + dic["enddate"].ToString() + "'";
        }
        
        uMESProcessResult result = new uMESProcessResult();
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = SelSQL;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public void getStockReturnApplyData(HttpContext context)
    {
        var SelSQL = GetStockReturnApplyzSql(context);
        if (!string.IsNullOrWhiteSpace(context.Request["mfgOrderID"].ToString()))
        {
            SelSQL += " AND sr.mfgOrderID='" + context.Request["mfgOrderID"].ToString() + "'";
        }
        var dt = DatabaseHelper.Query_ReturnDatTable(SelSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }

    public string GetStockReturnApplyzSql(HttpContext context) {
        var SelSQL = @"SELECT sr.ZSSTOCKRETURNAPPLYBILLID,sr.STOCKRETURNAPPLYBILLNO,sr.STOCKRETURNTYPE,m.MFGORDERNAME,u.ATTRIBUTEVALUE MachineNO
            ,P2.PRODUCTNAME,P.DESCRIPTION PRODUCTDESCRIPTION,sr.PRODUCTBATCHNO,sr.STOCKRETURNNUM,sr.STOCKRETURNREASON,sr.STATUS
            ,to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')CREATEDATE,e.FullNAME CREATEDATENAME
            ,to_char(sr.SUBMITDATE,'yyyy-MM-dd hh24:mi:ss')SUBMITDATE,e2.FullNAME SUBMITNAME
            ,to_char(sr.CONFIRMDATE,'yyyy-MM-dd hh24:mi:ss')CONFIRMDATE,e3.FullNAME CONFIRMNAME
            ,to_char(sr.STOCKRETURNDATE,'yyyy-MM-dd hh24:mi:ss')STOCKRETURNDATE,e4.FullNAME STOCKRETURNNAME
            ,sr.ERPSTOCKRETURNAPPLYBILLNO
            FROM ZSStockReturnApplyBill sr
            LEFT JOIN MFGORDER m ON m.MFGORDERID =sr.MFGORDERID
            LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
            LEFT JOIN PRODUCT p ON p.PRODUCTID =sr.PRODUCTID
            LEFT JOIN PRODUCTBASE p2 ON p2.PRODUCTBASEID =p.PRODUCTBASEID 
            LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =sr.CREATEEMPLOYEEID
            LEFT JOIN EMPLOYEE e2 ON e2.EMPLOYEEID =sr.SUBMITEMPLOYEEID
            LEFT JOIN EMPLOYEE e3 ON e3.EMPLOYEEID =sr.CONFIRMEMPLOYEEID
            LEFT JOIN EMPLOYEE e4 ON e4.EMPLOYEEID =sr.STOCKRETURNEMPLOYEEID
            WHERE nvl(sr.isuse,0)=0 ";
        return SelSQL;
    }
    
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void updateStockReturnBillData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var type = context.Request["type"].ToString();
        var sqlArr = new ArrayList();
        var tipText = "提交";
        var updateSQL = @"Update ZSStockReturnApplyBill set status=1,SUBMITDATE=sysdate,SUBMITEMPLOYEEID='"+m_UserInfo.EmployeeID+"' where ZSSTOCKRETURNAPPLYBILLID='{0}'";
        if (type == "confirm") { updateSQL = @"Update ZSStockReturnApplyBill set status=2,CONFIRMDATE=sysdate,CONFIRMEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where ZSSTOCKRETURNAPPLYBILLID='{0}'"; tipText = "确认"; }
        if (type == "return") { updateSQL = @"Update ZSStockReturnApplyBill set status=0,CONFIRMDATE=sysdate,CONFIRMEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where ZSSTOCKRETURNAPPLYBILLID='{0}'"; tipText = "退回"; }
        if (type == "erpno") { updateSQL = @"Update ZSStockReturnApplyBill set ERPSTOCKRETURNAPPLYBILLNO='{0}' where ZSSTOCKRETURNAPPLYBILLID='{1}'"; tipText = "保存"; }
        foreach (DataRow row in dt.Rows)
        {
            if (type == "erpno" && row["STATUS"].ToString() == "2")
            {
                sqlArr.Add(string.Format(updateSQL, row["ERPSTOCKRETURNAPPLYBILLNO"], row["ZSSTOCKRETURNAPPLYBILLID"]));
            }
            if (type == "confirm" || type == "return" || type == "submit")
            {
              sqlArr.Add(string.Format(updateSQL,row["ZSSTOCKRETURNAPPLYBILLID"]));
            }
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? tipText+"成功": tipText+"失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void deleteStockReturnBillData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var sqlArr = new ArrayList();
        var updateSQL = @"Update ZSStockReturnApplyBill set isuse=1 where ZSSTOCKRETURNAPPLYBILLID='{0}'";
        foreach (DataRow row in dt.Rows)
        {
            sqlArr.Add(string.Format(updateSQL, row["ZSSTOCKRETURNAPPLYBILLID"]));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    } 
}